package com.photography.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photography.common.Result;
import com.photography.entity.Order;
import com.photography.entity.OrderItem;
import com.photography.entity.Product;
import com.photography.entity.ProductReview;
import com.photography.exception.ErrorCode;
import com.photography.mapper.OrderMapper;
import com.photography.mapper.ProductReviewsMapper;
import com.photography.service.ProductReviewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
public class ProductReviewsServiceImpl extends ServiceImpl<ProductReviewsMapper, ProductReview> implements ProductReviewsService {
 @Resource
 private OrderMapper orderMapper;

 @Resource
 private ProductReviewsMapper productReviewsMapper;
    @Override
    @Transactional
    public Result addReview(ProductReview review) {
        // 参数校验
        if (review.getUserId() == null) {
            return Result.error("用户ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (review.getProductId() == null) {
            return Result.error("产品ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }
        if (review.getRating() == null || review.getRating() < 1 || review.getRating() > 5) {
            return Result.error("评分必须在1-5之间", ErrorCode.PARAM_ERROR.getCode());
        }
        if (!StringUtils.hasText(review.getContent())) {
            return Result.error("评论内容不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        // 检查用户是否购买过该产品
        List<Order> orders = orderMapper.findByUserId(review.getUserId());
        boolean hasPurchased = false;
        for (Order order : orders) {
            if ("已完成".equals(order.getOrderStatus()) && order.getOrderItemList() != null) {
                for (OrderItem item : order.getOrderItemList()) {
                    if (item.getProductId().equals(review.getProductId())) {
                        hasPurchased = true;
                        break;
                    }
                }
            }
            if (hasPurchased) {
                break;
            }
        }

        if (!hasPurchased) {
            return Result.error("您尚未购买该产品，无法发表评论", ErrorCode.USER_NO_PERMISSION.getCode());
        }

        // 检查是否已经评论过
        ProductReview existingReview = this.getOne(new QueryWrapper<ProductReview>().eq("user_id",review.getUserId()).eq("product_id",review.getProductId()));
        if (existingReview != null) {
            return Result.error("您已经评论过该产品", ErrorCode.DUPLICATE_OPERATION.getCode());
        }

        // 设置创建和更新时间
        Date now = new Date();
        review.setCreateTime(now);
        review.setUpdateTime(now);

        // 保存评论
        boolean result = this.save(review);
        if (result ) {
            return Result.success(review, "评论添加成功");
        } else {
            return Result.error("评论添加失败", ErrorCode.ERROR.getCode());
        }
    }

    @Override
    public Page<ProductReview> getProductReviewPage(Page<ProductReview> page, String rating) {
        // 创建查询条件
        LambdaQueryWrapper<ProductReview> queryWrapper = new LambdaQueryWrapper<>();

        // 添加筛选条件
        if (StringUtils.hasText(rating)) {
            queryWrapper.lt(ProductReview::getRating, rating);//小于此评分
        }

        // 按注册时间降序排序
        queryWrapper.orderByDesc(ProductReview::getCreateTime);

        // 执行分页查询
        return page(page, queryWrapper);
    }

    @Override
    @Transactional
    public Result deleteReview(Integer reviewId) {
        if (reviewId == null) {
            return Result.error("评论ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        boolean result = this.removeById(reviewId);
        if (result) {
            return Result.success("评论删除成功");
        } else {
            return Result.error("评论删除失败", ErrorCode.ERROR.getCode());
        }
    }



    @Override
    public Result findByProductId(Integer productId) {
        if (productId == null) {
            return Result.error("产品ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        List<ProductReview> reviews = productReviewsMapper.findByProductId(productId);
        return Result.success(reviews);
    }

    @Override
    public Result findByUserId(Integer userId) {
        if (userId == null) {
            return Result.error("用户ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        List<ProductReview> reviews = productReviewsMapper.findByUserId(userId);
        return Result.success(reviews);
    }

    @Override
    public Result getAverageRating(Integer productId) {
        if (productId == null) {
            return Result.error("产品ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        Double averageRating = productReviewsMapper.getAverageRating(productId);
        return Result.success(averageRating != null ? averageRating : 0.0);
    }

    @Override
    public Result getReviewCount(Integer productId) {
        if (productId == null) {
            return Result.error("产品ID不能为空", ErrorCode.PARAM_EMPTY.getCode());
        }

        Integer count = productReviewsMapper.getReviewCount(productId);
        return Result.success(count != null ? count : 0);
    }


}
